var app=getApp()
// var socketOpen = false;
//  const sock = require('../../utils/sockJs.js')
// const io=require('../../utils/weapp.socket.io.js')
// var socketUrl ='ws://chensanwa.top/api/eto/websocket'
// var frameBuffer_Data, session, SocketTask;
// const Stomp=require('../../utils/stomp.js').Stomp
// var websocket=require('../websocket/websocket.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
     submitStyle:'background-color:#02a0e9; color:white;',
     time:'2019-1-10 13:50',
     onenew:'',
     receiverID:'',
     receiverUrl:'',
     senderUrl:'',
     index:'',
     userType:'',
     pageNo:2,
     isFocus:false,
     newsArray:[],
  },
  submit:function(res){
     console.log(res)
     var v=res.detail.v
     this.setData({
       onenew:v
     })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // var msg={
    //   content:'11111',
    //   user:{}
    // }
    wx.pageScrollTo({
      scrollTop: 10000,
      success:function(res){
        console.log('成功')
      },
      fail:function(err){
        console.log('shibai ')
      }
    })
    var that=this
   
    console.log(options)
    try{
      
      var id = options.id
      this.setData({
        receiverID:id
      })
    }catch(err){
      console.log(err)
      console.log('获取接收者id失败')
    }
    try{
      var news=options.news
      console.log(news)
      if(news===undefined){
          console.log(111)
      }else{
        console.log(222)
        this.sendOneMessage(news)
      }
      
    }catch(err){
      console.log('未接收到数据')
      console.log(err)
    }
    try{
      var isAttention=options.attention
    }catch(err){
      this.showAttention()
    }
   
    wx.request({
      url: app.globalData.baseUrl+'user/id',
      header:{
        'cookie':'JSESSIONID='+wx.getStorageSync('sessionID')
      },
      success:function(res){
        console.log(res)
        var type = res.data.data.type
        that.setData({
          userType:type
        })
      }
    })
  },
  toUserData:function(event){
    var ty=this.data.userType
    var id=this.data.receiverID
    if(ty==2){
      wx.navigateTo({
        url: '/shouye/teacher/teacher?id='+id,
      })
    }else if(ty==4){
      wx.navigateTo({
        url: '/shouye/xiangqing/xiangqing?id='+id,
      })
    }else{
      wx.showToast({
        title: '该用户不是教师或机构',
        icon:'none',
        duration:5000
      })
    }
  },
  callback:function(res){
     console.log(res)
  },
  // socketStart:function(){
  //   const socket=(this.socket=io(
  //     socketUrl,
  //   ))
  //   socket.on('connect',()=>{

  //   })
  // },
  toJubao:function(event){
    var that=this
    wx.navigateTo({
      url: '../jubao/jubao?id='+that.data.receiverID,
    })
  },
   showAttention:function(){
     var readInegral
     wx.request({
       url: app.globalData.baseUrl + 'admin/integral/integral/1005',
       method: 'get',
       header: {
         'cookie': 'JSESSIONID=' + wx.getStorageSync('sessionID')
       },
       success: function (res) {
         readInegral = res.data.data.numerical * -1
         wx.showModal({
           title: '',
           content: '第一次发起聊天将会扣取' + readInegral + '积分',

         })
       }
     })

   },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },
  getNewsList:function(){
    
  }, 
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.websocket();
    this.getNews(1);
  },
  getNews:function(pageNo){
    var that=this
    wx.request({
      url: app.globalData.baseUrl+'chat/chatuser',
      
      data:{
         pageNo:pageNo,
        pageSize:50,
        receiver: that.data.receiverID
      },
      method:'get',
      header:{
        'cookie':'JSESSIONID='+wx.getStorageSync('sessionID')
      },
      
      success:function(res){
        console.log('获取单个消息列表')
        console.log(res)
        try{
          var receiver_avatar=res.data.data.receiver_avatarUrl
          var sender_avatar=res.data.data.sender_avatarUrl
          var userId=wx.getStorageSync('userID')
          var newList = res.data.data.chatUserList
          if(pageNo==1){
            newList = newList.reverse();
          }else{

          }
          
          that.setData({
            time: newList[0].gmtCreateFormat.substring(0, 16)
          })
          var resData=res.data.data
          that.setData({
            index:resData.chatUserList.length
          })
          for (var i = 0; i <resData.chatUserList.length;i++){
            var who = 'newsArray[' + i + '].who'
            var newsTxt = 'newsArray[' + i + '].newsTxt'
            var avatar = 'newsArray[' + i + '].avatar'
            if(userId==resData.chatUserList[i].sender){
            
              that.setData({
                senderUrl: sender_avatar,
                [who]:'me',
                [newsTxt]: newList[i].content,
                [avatar]:sender_avatar
              })
            }else{
             
              that.setData({
                receiverUrl: receiver_avatar,
                [who]: 'you',
                [newsTxt]: newList[i].content,
                [avatar]: receiver_avatar
              })
            }
          }
        }catch(err){
          console.log('暂时无消息')
        }
      
      },
      fail:function(res){
        wx.showToast({
          title: '获取消息失败',
          icon:'none'
        })
      }
    })
  },
  websocket:function(){
    var that=this
    var socketOpen = false
    var socketMsgQueue = []
    function sendSocketMessage(msg) {
      console.log('send msg:')
      console.log(msg);
      if (socketOpen) {
        wx.sendSocketMessage({
          data: msg
        })
      } else {
        socketMsgQueue.push(msg)
      }
    }
    console.log(typeof sendSocketMessage)
    var ws = {
      send: sendSocketMessage,
      onopen: null,
      onmessage: null
    }

    wx.connectSocket({
      url: 'wss://tongchengyouzhi.com/api/eto/websocket'
    })
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开！')

      socketOpen = true
      for (var i = 0; i < socketMsgQueue.length; i++) {
        sendSocketMessage(socketMsgQueue[i])
      }
      socketMsgQueue = []

      ws.onopen && ws.onopen()
    })

    wx.onSocketMessage(function (res) {
      console.log('收到onmessage事件:', res)
      ws.onmessage && ws.onmessage(res)
      console.log(res.data)
      console.log(typeof res.data)
      // var str = res.data.split(',')
      // console.log(str)
      // var newStr = str[3].split('=')
      // console.log(newStr)
      // var newsJsonObj=JSON.parse(res.data)
      // console.log(newsJsonObj)
    }) 
    wx.onSocketError(function(res){
      wx.showToast({
        title: '与服务器失去连接，请检查网络状况',
      })
    })

    var Stomp = require('../../utils/stomp.js').Stomp;
    Stomp.setInterval = function () { }
    Stomp.clearInterval = function () { }
    var client = Stomp.over(ws);

    var destination = '/user/' + wx.getStorageSync('userID') + '/message';
    client.connect({}, function (sessionId) {
      console.log('sessionId', sessionId)

      client.subscribe(destination, function (body, headers) {
        try{
          console.log('Body', body);
          // var str = body.body.split(',')
          // console.log(str)
          // var newStr = str[2].split('=')
          // console.log(newStr[1])
          // var i =0
          // console.log(i)
          var i=that.data.newsArray.length
          var newsData=JSON.parse(body.body)
          var who = 'newsArray[' + i + '].who'
          var newsTxt = 'newsArray[' + i + '].newsTxt'
          var avatar = 'newsArray[' + i + '].avatar'
          that.setData({
            [who]: 'you',
            [newsTxt]: newsData.content,
            [avatar]: that.data.receiverUrl,
            index: i + 1
          })
        }catch(err){
          console.log(err)
        }
       
        console.log('header', headers)
      });

      client.send(destination, { priority: 9 }, 'hello world!');
    })
  },
  submit: function (event) {
    var v = event.detail.v
   this.sendOneMessage(v)
   this.setData({
     isFocus:false
   })
  },
  sendOneMessage:function(msg){
    var that = this
    if(msg==''){
      wx.showModal({
        title: '',
        content: '您发送的消息为空，不能发送',
      })
    }else{
      wx.request({
        url: app.globalData.baseUrl + 'ws/message',
        method: 'POST',
        header: {
          'cookie': 'JSESSIONID=' + wx.getStorageSync('sessionID'),
          'content-type': "application/x-www-form-urlencoded"
        },
        data: {
          receiver: that.data.receiverID,
          msg: msg
        },
        success: function (res) {
          console.log('发送消息成功')
          console.log(res)
          var i = that.data.newsArray.length
          var who = 'newsArray[' + i + '].who'
          var newsTxt = 'newsArray[' + i + '].newsTxt'
          var avatar = 'newsArray[' + i + '].avatar'
          that.setData({
            [who]: 'me',
            [newsTxt]: msg,
            [avatar]: that.data.senderUrl,
            index: i + 1
          })
      },
      fail: function (err) {
        console.log('发送消息失败')
      }
    })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log(111)
    wx.onSocketClose(function (res) {
      console.log('socket已关闭')
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var pageNo=this.data.pageNo
    this.getNews(pageNo)
    this.setData({
      pageNo:this.data.pageNo+1
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})